package zooin.net;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;


public class VodList extends ListActivity {

	private String html;
	public function fc = new function();
	public AimsHandover hanover = new AimsHandover();
	public static String INTENT_VAL ="";
	public static String INTENT_VURL="videofilename";
	public static String INTENT_VPOS="videoposition";
	private String pCate;
	private String thisIP ,thisM ;
	public static String INTENT_USER="userid";
	private TextView title;
	private final int NP = 6; // 한 페이지에 출력할 리스트 갯수
    private int nPage = 1;   // 현재 페이지
    private int totalCnt = 1;   // 총 페이지 갯수
    private TextView printCnt;
    private String printCntVal;
	URL url = null;
	URLConnection conn;
	BufferedInputStream bis;
	Bitmap bm;
	String imgsrc;
	ProgressDialog progress;
	ArrayList<String> addrList=new ArrayList<String>();
	ArrayList<View> vList = new ArrayList<View>();
	// Thread run flag
	boolean imageViewflas = false;
	ImageView iv;
    
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//requestWindowFeature(Window.FEATURE_NO_TITLE);
		//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.setting);
     	fc.createThreadAndDialog(VodList.this);
     	
        SharedPreferences pref = getSharedPreferences("userInfo", MODE_PRIVATE);
        thisIP	= pref.getString("thisIP", "");
        pCate	= pref.getString("pCate", "");
        thisM	= pref.getString("thisM", "");

        intenter();

        title=(TextView) findViewById(R.id.title);
        title.setText(pCate); 
        	//cate Update
			SharedPreferences.Editor editor = pref.edit();
				editor.putString("pCate", pCate);
				editor.commit();
		//htmlValue(nPage);

		imageViewflas = false;
		handler.sendEmptyMessageDelayed(0, 100);
	}
	
	public void htmlValue(int nPage) {
        SharedPreferences prefs = getSharedPreferences("userInfo", MODE_PRIVATE);
        thisIP	= prefs.getString("thisIP", "");
        if("".equals(nPage) || nPage == 0){
    		html = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=3001&cate="+pCate+"&page=1&pageSize="+NP,this);
        }else{
    		html = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=3001&cate="+pCate+"&page="+nPage+"&pageSize="+NP,this);
        }
        list(html);
	}
	//데이타목록 뿌려주기
	public void list(String html) {
		
        SharedPreferences prefs = getSharedPreferences("userInfo", MODE_PRIVATE);
        thisIP	= prefs.getString("thisIP", "");
		try {
			String[] htmlRow,htmlCol;
			
			htmlRow =  html.split("ú");
			int rowLen = htmlRow.length-1;
			ArrayList<Set> s_orders = new ArrayList<Set>();
			ImageView imgView = (ImageView) findViewById(R.id.img_icon);
			
			totalCnt = Integer.valueOf(htmlRow[1]);		
			printCntVal = nPage+"/"+(int)Math.ceil(totalCnt/(double)NP);
		    printCnt = (TextView) findViewById(R.id.pageCnt);	
			if(totalCnt==0){
				printCnt.setText("");
			}else{
				printCnt.setText(printCntVal);
			}
/*			
			if(thisIP==""){
				stopImgThread();
			}*/
			
			for (int i = 2; i < rowLen; i++) {
				htmlCol = htmlRow[i].split("");
				try
				{	
					LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					View v = vi.inflate(R.layout.row, null);

					addrList.add(htmlCol[2]);
					vList.add(v);
					
					Set s = new Set(htmlCol[2],htmlCol[1], htmlCol[3], htmlCol[0], htmlCol[4],v);
					//Set s = new Set(bm, htmlCol[1] , htmlCol[3], htmlCol[0], htmlCol[4]);//hit추가
					s_orders.add(s);
				}catch(Exception e){}
			}
			
			SettingAdapter s_adapter = new SettingAdapter(this, R.layout.row, s_orders);
			setListAdapter(s_adapter);

		} catch (Exception e) {
			//Toast.makeText(VodList.this, "error", Toast.LENGTH_SHORT).show();
		}
	}

	private class SettingAdapter extends ArrayAdapter<Set>{
		private ArrayList<Set> items;
	
		public SettingAdapter(Context context,int textViewResourceId,ArrayList<Set> items){
			super(context, textViewResourceId, items);
			this.items = items;
		}
		
		public View getView(int position, View convertView, ViewGroup parent){

			Set s = items.get(position);
			View v = s.getView(); // convertView;
			if(v==null){
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.row, null);
			}
			
			if(s != null){
				ImageView iv = (ImageView)v.findViewById(R.id.img_icon);
				TextView tv = (TextView)v.findViewById(R.id.label);
				TextView tv2 = (TextView)v.findViewById(R.id.label2);
				TextView vodIdStr = (TextView)v.findViewById(R.id.vod_id);
				TextView hit = (TextView)v.findViewById(R.id.hit);
				
				if(tv != null){tv.setText(s.getText());}
				if(tv2 != null){tv2.setText(s.getSubText());}
				if ( vodIdStr != null ){vodIdStr.setText(s.getVodId());}
				if ( hit != null ){hit.setText(s.getHit());}
				
				
		        v.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						TextView vodIdString = (TextView)v.findViewById(R.id.vod_id);
						//TextView hitString = (TextView)v.findViewById(R.id.hit);
						// Vod Play Url 검색
						try {
							html = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=3002&vodID="+ vodIdString.getText().toString() +"&deviceType="+thisM,VodList.this);
							if( "".equals(html) || html == null){
								Toast.makeText(VodList.this, "정보수신에 실패했습니다. \n 잠시후 다시 이용하세요." , Toast.LENGTH_SHORT).show();	
					    	}else{
								int htmlValue1 = Integer.parseInt(html.split("ú")[0]);	
					        	if(htmlValue1==0){
					        		String htmlValue=html.split("ú")[1];	
					        		String url = htmlValue.split("")[0].toString();
					        		String rtime = htmlValue.split("")[1].toString();
					        		if("".equals(url) || url == null){
					        			Toast.makeText(VodList.this, "재생정보가  존재하지 않습니다." , Toast.LENGTH_SHORT).show();	
					        		}else{
						        		//hit 올림
										html = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=3003&vodID="+ vodIdString.getText().toString(),VodList.this);
						        		Intent intent = new Intent(VodList.this,ViewVideo.class);
											intent.putExtra(INTENT_VURL, url);
											intent.putExtra(INTENT_VPOS, "0");
											intent.putExtra(INTENT_VAL,vodIdString.getText().toString()+",VOD");
				        				startActivity(intent);
				        				//VodList.this.finish();
					        		}
					        	}else{
					        		Toast.makeText(VodList.this, "컨텐츠가 존재하지 않습니다." , Toast.LENGTH_SHORT).show();	
					        	}
					    	}//html 존재
							// Vod Player 호출
						} catch (Exception e) {}
						
					}
				});
			}
			return v;
		}
	}
	
	public class Set{
		private String textSet;
		private String subText;
		private String vodId; 
		private String hit; 
		private String bitmapimgSrc;
		private View v;

		public Set(String btimg, String textSet, String subText, String vodId, String hit, View v)
		{
			this.bitmapimgSrc = btimg;
			this.textSet = textSet;
			this.subText = subText;
			this.vodId = vodId;
			this.hit = hit;
			this.v = v;
		}
	
		public String getText(){
			return textSet;
		}
		
		public String getSubText(){
			return subText;
		}
		
		public String getVodId(){
			return vodId;
		}

		public String getHit(){
			return hit;
		}
		public View getView()
		{
			return this.v;
		}
	}
	  
	//매뉴 만들기
    public boolean onCreateOptionsMenu(Menu menu) {
    	    boolean result = super.onCreateOptionsMenu(menu);
    	    MenuInflater menuInflator = new MenuInflater(this);
    	    menuInflator.inflate(R.menu.list_setting, menu);
    	    return result;
    }
    //menu 이벤트처리
    public boolean onOptionsItemSelected(MenuItem item){
    	switch (item.getItemId()) {
		case R.id.prev:
			if( nPage > 1 ){
				nPage--;
				htmlValue(nPage);
				imageViewflas = true;
    			handler.sendEmptyMessage(0);
			}else{
				if ( nPage < 1) nPage=1;
				Toast.makeText(VodList.this, "First Page", Toast.LENGTH_SHORT).show();
			}
			return true;
		case R.id.next:
			if( nPage < (int)Math.ceil(totalCnt/(double)NP)){
				nPage++;
				htmlValue(nPage);
				imageViewflas = true;
    			handler.sendEmptyMessage(0);
			}else{
				if ( nPage > (int)Math.ceil(totalCnt/(double)NP) ) nPage=(int)Math.ceil(totalCnt/(double)NP);
				Toast.makeText(VodList.this, "Last Page", Toast.LENGTH_SHORT).show();
			}
			return true;
		case R.id.home:
			Intent intent = new Intent(VodList.this,MainCategory.class);
			startActivity(intent);
			finish();
			return true;
		case R.id.refresh:
			htmlValue(nPage);
			imageViewflas = true;
			handler.sendEmptyMessage(0);
			return true;
		case R.id.setting:
			Intent intent2 = new Intent(VodList.this,setList.class);
			startActivity(intent2);
			finish();
			return true;
		}
    	
    	return (super.onOptionsItemSelected(item));
    }
    
    @Override
    public void onBackPressed() {
    	VodList.this.finish();
	}
    
    public void intenter(){
    	Intent intent = getIntent();
    }
    
    //핸들러 객체 정의하기
    Handler handler=new Handler(){
    	public void handleMessage(android.os.Message msg) {
    		if ( imageViewflas == true)
    		{
    			for( int i=0; i < addrList.size(); i++)
				{
					try {

				        HttpClient client = new DefaultHttpClient();  
				        HttpGet get = new HttpGet(addrList.get(i));
				        HttpResponse responseGet = client.execute(get);  
				        
				        InputStream is = responseGet.getEntity().getContent();
				        bis = new BufferedInputStream(is, (int)responseGet.getEntity().getContentLength());
				        bm = BitmapFactory.decodeStream(bis);
						iv = (ImageView)vList.get(i).findViewById(R.id.img_icon);
						
						if(iv != null){
							iv.setImageBitmap(bm);
			    			iv.setScaleType(ScaleType.FIT_XY);
						}

						bis.close();
						is.close();
					} catch (Exception e) {}
				}
    		}
    		else
    		{
    			htmlValue(nPage);
        		fc.closeThreadAndDialog();
    			imageViewflas = true;
    			handler.sendEmptyMessage(0);
	    		// Toast.makeText(VodList.this, "TEST", 0).show();
    		}
    	}
    };
    
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		handler.removeMessages(0);
		//handler2.removeMessages(0);
		//stopImgThread();
	}
	


}
